package com.xinmachong.jwt_demo.interceptor;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xinmachong.jwt_demo.util.JWTUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author meyer@HongYe
 *
 * 和Filter相比，Interceptor拦截范围不是后续整个处理流程，而是仅针对Controller拦截
 *
 * 使用HandlerInterceptor的场景：
 *
 * 鉴权，可以使用HandlerInterceptor但是Filter是更佳的选择。
 * 审计日志，记录每一个请求。
 * Token解析或校验。
 * Handler执行时间统计。
 */
public class JWTInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map<String,Object> map = new HashMap<>();
        String token = request.getHeader("token");
        try {
            JWTUtils.verify(token);
            return true;
        }catch (SignatureVerificationException e){
            map.put("msg","无效签名");
        }catch (TokenExpiredException e){
            map.put("msg","token过期");
        }catch (AlgorithmMismatchException e){
            map.put("msg","token算法不一致");
        }catch (Exception e){
            map.put("msg","token无效");
        }
        map.put("code",505);
        map.put("data",false);
        String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
        return false;
    }
}
